package com.qf.test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.pojo.User;
import org.junit.Test;
import org.springframework.util.SerializationUtils;
import redis.clients.jedis.Jedis;

import java.util.Date;

/**
 * 存储对象到Redis服务
 */
public class Demo2 {


    /**
     * 推荐采用这种方式.
     * @throws JsonProcessingException
     */
    @Test
    public void setJSON() throws JsonProcessingException {
        //1. 创建连接
        Jedis jedis = new Jedis("192.168.41.41",6379);
        //-----------------------------------
        //2. 操作
        User user = new User(1,"王大拿",new Date());
        ObjectMapper mapper = new ObjectMapper();
        String value = mapper.writeValueAsString(user);

        jedis.set("user",value);
        //-----------------------------------
        //3. 释放资源
        jedis.close();
    }


    /**
     * 不推荐使用
     */
    @Test
    public void setByteArray(){
        //1. 创建连接
        Jedis jedis = new Jedis("192.168.41.41",6379);
        //-----------------------------------
        //2. 操作
        User user = new User(1,"王大拿",new Date());
        byte[] value = SerializationUtils.serialize(user);
        byte[] key = SerializationUtils.serialize("user");

        jedis.set(key,value);
        //-----------------------------------
        //3. 释放资源
        jedis.close();
    }

}
